package com.authority.framework.web.controller;

import com.authority.framework.log.Log;
import com.authority.framework.log.enums.BusinessType;
import com.authority.framework.web.domain.*;
import com.authority.framework.web.service.SysDeptService;
import com.authority.framework.web.service.SysMenuService;
import com.authority.framework.web.service.SysRoleService;
import com.authority.framework.base.util.DateUtils;
import com.authority.framework.base.util.ShiroUtils;
import com.authority.framework.base.util.StringUtils;
import com.authority.framework.base.util.laydata.LayDatas;
import com.authority.framework.base.util.laydata.PageUtils;
import com.authority.framework.base.util.laydata.ResultModel;
import com.authority.framework.base.util.laydata.ResultTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.authority.framework.base.util.EncryptPassword.encryptPassword;

/**
 * @program: authority
 * @description: 角色控制层
 * @author: Mr.Yan
 * @create: 2018-11-16 15:51
 **/
@Controller
@RequestMapping(value = "/sysroleCon")
public class SysRoleController {

	private static final Logger log = LoggerFactory.getLogger(SysUserController.class);

	@Autowired
	private SysRoleService sysRoleService;

	@Autowired
	private SysMenuService sysMenuService;

	@Autowired
	private SysDeptService sysDeptService;

	private Map<String, Object> paramMap;//参数

	private Map<String, Object> resultMap;//返回值

	/**
	 * 用户界面获取角色集
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/findAll")
	public ResultModel findAll(HttpServletRequest request, HttpServletResponse response) {
		List<SysRoleEntity> roles = null;
		resultMap = new HashMap<>();
		try {
			roles = sysRoleService.findAll(SysRoleEntity.class);
			resultMap.put("roles", roles);
			return ResultTools.result(0, "", resultMap);
		}
		catch (Exception e) {
			return ResultTools.result(404, e.getMessage(), resultMap);
		}
	}

	/**
	 * @Description: 获取角色所有级
	 * @Param:
	 * @return:
	 * @Author: Mr.Yan
	 * @Date: 2018/12/6
	 */
	@GetMapping(value = "/list")
	@ResponseBody
	public LayDatas list(HttpServletRequest request, HttpServletResponse response,
			PageUtils pageUtils) {
		//  获取登陆用户信息
		SysUserEntity userEntity = ShiroUtils.getSubjectUser();
		if (!userEntity.isAdmin()) {
			pageUtils.setPara("roleIds", userEntity.getRoleIds());
		}
		return sysRoleService.pageLayInfo("system/SysRoleSql", SysRoleEntity.class, pageUtils);
	}

	/**
	 * @Description: 角色添加
	 * @Param:
	 * @return:
	 * @Author: Mr.Yan
	 * @Date: 2018/12/13
	 */

	@Log(title = "角色管理", businessType = BusinessType.INSERT)
	@RequestMapping("/insert")
	@ResponseBody
	public ResultModel insert(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Map<String, Object> ajaxMap) {
		try {
			// 菜单权限ids
			String menuIds = (String) ajaxMap.get("menuIds");
			//  获取登陆用户信息
			SysUserEntity userEntity = ShiroUtils.getSubjectUser();
			ajaxMap.put("createBy", userEntity.getUserName());
			//  获取当前时间
			String time = DateUtils.getTime();
			ajaxMap.put("createTime", time);

			//  添加角色
			Integer roleId = sysRoleService.insert(SysRoleEntity.class, ajaxMap);
			//  添加角色的菜单
			if (StringUtils.isNotEmpty(menuIds)) {
				String[] menuIdSplit = menuIds.split(",");
				for (int i = 0; i < menuIdSplit.length; i++) {
					paramMap = new HashMap<>();
					paramMap.put("roleId", roleId);
					paramMap.put("menuId", menuIdSplit[i]);
					//  添加角色和菜单关系
					try {
						Integer insertSysRoleMenu = sysRoleService.commonInsert("system/SysRoleMenu.insertSysRoleMenu", paramMap);
						if (insertSysRoleMenu < 1) {
							return ResultTools.result(404, "添加角色菜单''失败", null);
						}
					}
					catch (Exception e) {
						return ResultTools.result(404, "添加角色菜单''失败", null);
					}
				}
			}
			return ResultTools.result(0, "", null);
		}
		catch (Exception e) {
			log.error("添加角色信息出现未知错误" + e.getMessage());
			return ResultTools.result(404, "添加角色信息出现未知错误", null);
		}
	}

	/**
	 * @Description: 打开修改角色信息界面之前，获取角色详细信息
	 * @Param:
	 * @return:
	 * @Author: Mr.Yan
	 * @Date: 2018/12/7
	 */
	@ResponseBody
	@RequestMapping(value = "/openRoleUpdate")
	public ModelAndView openRoleUpdate(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(name = "roleId", required = false) Integer roleId) {
		resultMap = new HashMap<>();
		// 查询角色表信息
		SysRoleEntity sysRoleEntity = sysRoleService.findByPrimaryKey(SysRoleEntity.class, roleId);
		// 查询角色菜单信息
		List<SysMenuEntity> menuEntitys = sysMenuService.findListByRoleId(roleId);
		String menuIds = "";
		if (menuEntitys.size() > 0) {
			for (SysMenuEntity menu : menuEntitys) {
				menuIds += menu.getMenuId() + ",";
			}
			menuIds = menuIds.substring(0, menuIds.length() - 1);
		}
		ModelAndView mv = new ModelAndView();
		mv.setViewName("web/system/role/role_update");
		mv.addObject("role", sysRoleEntity);
		mv.addObject("menuIds", menuIds);
		return mv;
	}

	/**
	 * @Description: 更新角色信息
	 * @Param:
	 * @return:
	 * @Author: Mr.Yan
	 * @Date: 2018/12/7
	 */
	@Log(title = "角色管理", businessType = BusinessType.UPDATE)
	@ResponseBody
	@RequestMapping(value = "/update")
	public ResultModel update(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Map<String, Object> ajaxMap) {
		try {
			// 菜单权限ids
			String menuIds = (String) ajaxMap.get("menuIds");
			String roleId = (String) ajaxMap.get("roleId");
			//  获取登陆用户信息
			SysUserEntity userEntity = ShiroUtils.getSubjectUser();
			ajaxMap.put("updateBy", userEntity.getUserName());
			//  获取当前时间
			String time = DateUtils.getTime();
			ajaxMap.put("updateTime", time);

			//  添加角色
			Integer isUpdate = sysRoleService.update(SysRoleEntity.class, ajaxMap);
			//删除角色以前菜单
			Integer deleteUserPostSize = sysRoleService.deleteRoleMenu(roleId);
			//  添加角色的菜单
			if (StringUtils.isNotEmpty(menuIds)) {
				String[] menuIdSplit = menuIds.split(",");
				for (int i = 0; i < menuIdSplit.length; i++) {
					paramMap = new HashMap<>();
					paramMap.put("roleId", roleId);
					paramMap.put("menuId", menuIdSplit[i]);
					//  添加角色和菜单关系
					try {
						Integer insertSysRoleMenu = sysRoleService.commonInsert("system/SysRoleMenu.insertSysRoleMenu", paramMap);
						if (insertSysRoleMenu < 1) {
							return ResultTools.result(404, "更新角色菜单''失败", null);
						}
					}
					catch (Exception e) {
						return ResultTools.result(404, "更新角色菜单''失败", null);
					}
				}
			}
			return ResultTools.result(0, "", null);
		}
		catch (Exception e) {
			log.error("更新角色信息出现未知错误" + e.getMessage());
			return ResultTools.result(404, "更新角色信息出现未知错误", null);
		}
	}

	/**
	 * 删除 角色信息
	 *
	 * @param request
	 * @param response
	 * @param roleIds
	 * @return
	 */
	@Log(title = "角色管理", businessType = BusinessType.DELETE)
	@ResponseBody
	@RequestMapping(value = "/deleteRole")
	public ResultModel deleteRole(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(name = "roleIds", required = false) String roleIds) {
		try {
			String[] roleIdArr = roleIds.split(",");
			for (String roleId : roleIdArr) {
				paramMap = new HashMap<>();
				paramMap.put("roleId", roleId);
				paramMap.put("delFlag", 2);
				//  获取当前时间
				String time = DateUtils.getTime();
				//  获取登陆用户信息
				SysUserEntity userEntity = ShiroUtils.getSubjectUser();
				paramMap.put("updateTime", time);
				paramMap.put("updateBy", userEntity.getUserName());
				Integer update = sysRoleService.update(SysRoleEntity.class, paramMap);
				if (update < 1) {
					return ResultTools.result(404, "删除角色信息出现未知错误", null);
				}
			}
			return ResultTools.result(0, "", null);
		}
		catch (Exception e) {
			log.error("删除角色信息出现未知错误" + e.getMessage());
			return ResultTools.result(404, "删除角色信息出现未知错误", null);
		}
	}

	/**
	 * @Description: 打开修改角色数据权限界面之前，获取角色数据权限详细信息
	 * @Param:
	 * @return:
	 * @Author: Mr.Yan
	 * @Date: 2018/12/14
	 */
	@ResponseBody
	@RequestMapping(value = "/openOperate")
	public ModelAndView openOperate(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(name = "roleId", required = false) String roleId) {
		ModelAndView mv = new ModelAndView();
		// 获取角色的部门权限
		List<SysDeptEntity> deptEntitys = sysDeptService.findListByRoleId(roleId);
		String deptIds = "";
		if (deptEntitys.size() > 0) {
			for (SysDeptEntity dept : deptEntitys) {
				deptIds += dept.getDeptId() + ",";
			}
			deptIds = deptIds.substring(0, deptIds.length() - 1);
		}
		mv.addObject("deptIds", deptIds);
		mv.addObject("roleId", roleId);
		mv.setViewName("web/system/role/deptTree/deptTree");
		return mv;
	}

	@Log(title = "数据权限", businessType = BusinessType.GRANT)
	@ResponseBody
	@RequestMapping(value = "/updateOperate")
	public ResultModel updateOperate(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(name = "deptIds", required = false) String deptIds,
			@RequestParam(name = "roleId", required = false) String roleId){
		try {
			//删除角色以前部门权限
			Integer deleteRoleDeptSize = sysRoleService.deleteRoleDept(roleId);
			//  添加角色的部门
			if (StringUtils.isNotEmpty(deptIds)) {
				String[] deptIdSplit = deptIds.split(",");
				for (int i = 0; i < deptIdSplit.length; i++) {
					paramMap = new HashMap<>();
					paramMap.put("roleId", roleId);
					paramMap.put("deptId", deptIdSplit[i]);
					//  添加角色和部门关系
					try {
						Integer insertSysRoleDept = sysRoleService.commonInsert("system/SysRoleDept.insertSysRoleDept", paramMap);
						if (insertSysRoleDept < 1) {
							return ResultTools.result(404, "更新角色数据权限''失败", null);
						}
					}
					catch (Exception e) {
						return ResultTools.result(404, "更新角色数据权限''失败", null);
					}
				}
			}
			return ResultTools.result(0, "", null);
		}
		catch (Exception e) {
			log.error("更新数据权限信息出现未知错误" + e.getMessage());
			return ResultTools.result(404, "更新数据权限信息出现未知错误", null);
		}
	}
}
